package com.igoal.admin.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.igoal.admin.service.MemberMailService;
import com.igoal.admin.web.model.AdminBaseModel;
import com.igoal.admin.web.model.AdminMemberMailModel;
import com.igoal.dto.MemberMailDTO;

@Controller
public class AdminMemberMailController extends AdminBaseController {
	private static final Log logger = LogFactory.getLog(AdminMemberMailController.class);
	
	@Autowired
	MemberMailService memberMailService;
	
	@RequestMapping(method=RequestMethod.GET, value="/admin/memberMail.html")
	public String showForm(ModelMap modelMap, @RequestParam(required=false, value="id") Long id, HttpServletRequest request){
		AdminMemberMailModel model = new AdminMemberMailModel();
		model.setList(memberMailService.getAll());
		
		if(id != null){
			MemberMailDTO dto = memberMailService.get(id);
			if(dto != null){
				model.setMemberMail(dto);
				model.setActiveTab(AdminMemberMailModel.FORM_TAB);
			}else{
				model.setActiveTab(AdminMemberMailModel.LIST_TAB);
			}
		}else{
			model.setActiveTab(AdminMemberMailModel.LIST_TAB);
		}
		
		initLeftPage(model, request);
		initRightPage(model, request);
		
		applyModel(modelMap, model);
		
		return getViewPrefix() + "memberMail";
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/admin/memberMail.html")
	public String sendMailToMember(ModelMap modelMap, @ModelAttribute("memberMail") AdminMemberMailModel model, 
			HttpServletRequest request){
		
		MemberMailDTO memberMail = memberMailService.save(model.getMemberMail());
		
		model = new AdminMemberMailModel();		
		model.setMemberMail(memberMail);
		model.setList(memberMailService.getAll());
		model.setActiveTab(AdminMemberMailModel.LIST_TAB);
		
		applyModel(modelMap, model);
		
		return getViewPrefix() + "memberMail";
	}
	
	@Override
	public void initLeftPage(AdminBaseModel baseModel,
			HttpServletRequest request) {
	}

	@Override
	public void initRightPage(AdminBaseModel baseModel,
			HttpServletRequest request) {
	}

}
